package com.ultrasoft.farmasoft.repository;

import java.util.List;

import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;
import javax.persistence.TypedQuery;

import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Transactional;

import com.ultrasoft.farmasoft.domain.Composition;

@Repository(value = "compositionDao")
@Transactional(readOnly = false)
public class CompositionDaoImpl implements CompositionDao {

	private EntityManager em = null;
	@PersistenceContext
	public void setEntityManager(EntityManager em) {
		this.em = em;
	}
	
	public List<Composition> getListComposition() {
		TypedQuery<Composition> q = em.createNamedQuery("Composition.findAll",Composition.class);
    	return q.getResultList();
	}

	public List<Composition> getListComposition(Integer compositionId) {
		TypedQuery<Composition> q = em.createNamedQuery("Composition.findByCompositionId",Composition.class);
    	q.setParameter("compositionId",compositionId);
    	return q.getResultList();
	}

	public List<Composition> getListComposition(boolean active) {
		TypedQuery<Composition> q = em.createNamedQuery("Composition.findByActive",Composition.class);
    	q.setParameter("active",active);
    	return q.getResultList();
	}

	public List<Composition> getListComposition(Integer compositionId,boolean active) {
		TypedQuery<Composition> q = em.createNamedQuery("Composition.findByCompositionIdByActive",Composition.class);
    	q.setParameter("compositionId",compositionId);
    	q.setParameter("active",active);
    	return q.getResultList();
	}

	public List<Composition> getListComposition(Integer providerId,Integer productId,boolean active) {
		TypedQuery<Composition> q = em.createNamedQuery("Composition.findByProviderIdByProductIdByActive",Composition.class);
    	q.setParameter("providerId",providerId);
    	q.setParameter("productId",productId);
    	q.setParameter("active",active);
    	return q.getResultList();
	}
	
	public Composition findByCompositionId(Integer compositionId) {
		Composition res=null;
		try {
			res=em.find(Composition.class,compositionId);
		} catch (Exception e) {
			// TODO: handle exception
		}
    	return res;
	}

	public void update(Composition composition) {
		em.merge(composition);
	}
	
	public void remove(Integer providerId,Integer productId) {
		Query q = em.createNamedQuery("Composition.deleteByProviderIdByProductId");
		q.setParameter("providerId",providerId);
		q.setParameter("productId",productId);
		q.executeUpdate();
	}
	
	public void remove(Composition composition) {
		em.remove(em.getReference(Composition.class,composition.getCompositionId()));
	}

	public void add(Composition composition) {
		em.persist(composition);
	}
}
